<template>
	<view class="content">
		<view class="main">

			<!-- <view style="font-weight: bold;color: orangered;font-size: 28rpx;">注意：图片识别不能保证完全准确，请认真核对识别后的数据与销售单是否一致！</view> -->
			<view class="menu_name">
				发货信息
				<view style="font-size: 24rpx;color: #aaa;margin: 0 0 0 6rpx;">粘贴发货信息到输入框</view>
			</view>
			<textarea class="et_desc" placeholder="粘贴发货信息到输入框" @input="onInputDesc" />

			<view class="btn_analysis" @click.stop="onAnalysis">识别</view>

			<!-- 收货人部分 -->
			<view class="item_div">

				<view class="item_sub_div">
					<view class="item_sub_txt">接货地址</view>
				</view>

				<view class="item_sub_div">
					<view class="item_sub_txt" style="display: none;">详细地址</view>
					<textarea class="et_sub_txt" style="width: 100%;;" placeholder="请输入接货地址" @input="onInputPickAddress" :value="info.pick_address" />
				</view>

				<view style="width: 100%;height: 1rpx;background: #ededed;margin: 0rpx 0 0 0;"></view>

				<view class="item_sub_div">
					<view class="item_sub_txt">货物</view>
					<input class="et_sub_txt" placeholder="请输入货物信息" maxlength="999" @input="onInputGoodsInfo" :value="info.goods_info" />
				</view>

				<view style="width: 100%;height: 1rpx;background: #ededed;margin: 0rpx 0 0 0;"></view>

				<view class="item_sub_div">
					<view class="item_sub_txt">发货人</view>
					<input class="et_sub_txt" placeholder="请输入发货人" maxlength="99" @input="onInputSenderName" :value="info.sender_name" />
				</view>

				<view style="width: 100%;height: 1rpx;background: #ededed;margin: 0rpx 0 0 0;"></view>

				<view class="item_sub_div">
					<view class="item_sub_txt">发货电话</view>
					<input class="et_sub_txt" placeholder="请输入发货电话" type="number" maxlength="99" @input="onInputSenderMobile" :value="info.sender_mobile" />
				</view>

				<view style="width: 100%;height: 1rpx;background: #ededed;margin: 0rpx 0 0 0;"></view>

				<view class="item_sub_div">
					<view class="item_sub_txt">收货人</view>
					<input class="et_sub_txt" placeholder="请输入收货人" maxlength="99" @input="onInputReceiverName" :value="info.receiver_name" />
				</view>

				<view style="width: 100%;height: 1rpx;background: #ededed;margin: 0rpx 0 0 0;"></view>

				<view class="item_sub_div">
					<view class="item_sub_txt">收货电话</view>
					<input class="et_sub_txt" placeholder="请输入收货电话" type="number" maxlength="99" @input="onInputReceiverMobile" :value="info.receiver_mobile" />
				</view>

				<view style="width: 100%;height: 1rpx;background: #ededed;margin: 0rpx 0 0 0;"></view>

				<view class="item_sub_div">
					<view class="item_sub_txt">收货地址</view>
					<input class="et_sub_txt" placeholder="请输入收货地址" maxlength="999" @input="onInputReceiverAddress" :value="info.receiver_address" />
				</view>

				<view style="width: 100%;height: 1rpx;background: #ededed;margin: 0rpx 0 0 0;"></view>

				<view class="item_sub_div">
					<view class="item_sub_txt">备注</view>
					<input class="et_sub_txt" placeholder="请输入备注" maxlength="999" @input="onInputRemark" :value="info.remark" />
				</view>

				<view style="width: 100%;height: 1rpx;background: #ededed;margin: 0rpx 0 0 0;"></view>

			</view>

			<view class="btn_ok" @click="onOK">确定</view>

		</view>

	</view>
</template>

<script>
	import { getUInfo, isEmpty } from '@/util/util.js'
	import { chooseAndUploadImg, chooseAndUploadVideo } from '@/util/uni_util.js'
	const CryptoJS = require('@/util/ext/crypto-js.min.js')
	export default {
		data() {
			return {
				detail: {}, // 运单详情
				img_url: '', // 选择的照片

				desc: '', // 粘贴的发货信息

				// 开单信息
				info: {
					pick_address: '',
					sender_name: '',
					sender_mobile: '',
					receiver_name: '',
					receiver_mobile: '',
					receiver_address: '',
					goods_info: '',
					remark: '',
				},
			}
		},

		onLoad(opts) {
			if (getUInfo() && getUInfo().id) {

			} else {
				uni.redirectTo({ url: '/pages/login/login' })
			}
			// 扫码
			uni.$on('onGetQrCode', (data) => {
				let { qr_code, od_num, startCity, toCity, goods } = JSON.parse(data.qr_code_data)
				this.detail = { startCity, toCity, goods }
				console.log('this.detail  = ', this.detail);
			})
		},

		onUnload() {
			uni.$off('onGetQrCode', () => {})
		},

		methods: {

			// 识别粘贴的发货信息
			onAnalysis() {
				uni.showToast({ icon: 'none', title: '识别中，请稍候' })
				if (!this.desc) {
					uni.showToast({ icon: 'none', title: '请输入发货信息' })
					return
				}
				this.arkAnalyzeTxt()
			},
			// 监听:粘贴的货物信息
			onInputDesc(e) {
				this.desc = e.detail.value
			},
			// 输入货物名称
			onInputGoodsName(e) {
				this.info.goods_name = e.detail.value
			},
			// 输入件数
			onInputNum(e) {
				this.info.num = e.detail.value
			},
			// 输入备注
			onInputRemark(e) {
				this.info.remark = e.detail.value
			},
			// 输入体积
			onInputVolume(e) {
				this.info.volume = e.detail.value
			},
			// 输入重量
			onInputWeight(e) {
				this.info.weight = e.detail.value
			},
			// 监听:输入取货地址
			onInputPickAddress(e) {
				this.info.pick_address = e.detail.value
			},
			// 监听:输入货物信息
			onInputGoodsInfo(e) {
				this.info.goods_info = e.detail.value
			},
			// 监听:输入收货人地址
			onInputReceiverAddress(e) {
				this.info.receiver_address = e.detail.value
			},
			// 监听:收货电话
			onInputReceiverMobile(e) {
				this.info.receiver_mobile = e.detail.value
			},
			// 监听:收货客户名称
			onInputReceiverName(e) {
				this.info.receiver_name = e.detail.value
			},
			// 监听:发货人
			onInputSenderName(e) {
				this.info.sender_name = e.detail.value
			},
			// 监听:发货电话
			onInputSenderMobile(e) {
				this.info.sender_mobile = e.detail.value
			},

			// 选择上传照片
			async onSelImg() {
				let res = await chooseAndUploadImg()
				// console.log('上传结果 = ', res);
				this.img_url = res
				this.arkAnalyze()
			},
			// 预览照片
			onPreviewImg(current) {
				uni.previewImage({
					current,
					urls: [this.img_url],
					success: (res) => {},
					fail: (res) => {
						uni.showToast({ icon: 'none', title: '查看图片失败' })
					}
				})
			},
			// 删除照片
			onDelImg(index) {
				let that = this
				uni.showModal({
					title: '提示',
					content: '是否删除该照片？',
					success: (res) => {
						if (res.confirm) {
							that.img_url = ''
						}
					},
				})
			},

			// 提交上报
			onOK() {
				if (!this.info.receiver_name) {
					uni.showToast({ icon: 'none', title: '请输入客户名' })
					return
				}
				if (!this.info.receiver_mobile) {
					uni.showToast({ icon: 'none', title: '请输入收货电话' })
					return
				}
				if (!this.info.receiver_address) {
					uni.showToast({ icon: 'none', title: '请输入收货地址' })
					return
				}
				if (!this.info.goods_name) {
					uni.showToast({ icon: 'none', title: '请输入货物名称' })
					return
				}
				if (!this.info.num) {
					uni.showToast({ icon: 'none', title: '请输入货物件数' })
					return
				}
				if (!this.info.weight) {
					uni.showToast({ icon: 'none', title: '请输入货物重量' })
					return
				}
				uni.showModal({
					title: '提示',
					content: '确认开单？',
					success: (res) => {
						res.confirm && this.postData()
					}
				})
			},

			// 接口:AI解析txt $arkAnalyzeTxt
			async arkAnalyzeTxt() {
				let that = this
				uni.showLoading({ title: '识别中', mask: true, })
				let user_token = getUInfo().token

				let text = '分析图片中客户简称中的姓名(只要人的姓名)、客户地址、客户电话、总件数、总重量，摘要，指定，以json格式输出，键名分别为name，address，phone，num，weight，remark，sign'

				let prms = {
					"model": "doubao-1-5-ui-tars-250428",
					"messages": [{
						"content": [{
							"text": `${this.desc}。分析以上内容中的接货地址、货物信息、发货人、发货电话，收货人，收货电话，收货地址，以json格式输出，
							键名分别为address、goods_info、send_name、send_phone、receive_name、receive_phone、receive_address`,
							"type": "text"
						}],
						"role": "user"
					}]
				}

				let response = await that.$arkAnalyzeTxt(prms)
				console.log('AI解析TXT.response =  ', response);
				if (response && response.choices && response.choices.length > 0) {
					let content = JSON.parse(response.choices[0].message.content)
					console.log('content = ', content);
					if (content) {
						that.info.pick_address = content.address
						that.info.goods_info = content.goods_info
						that.info.sender_name = content.send_name
						that.info.sender_mobile = content.send_phone
						that.info.receiver_name = content.receive_name
						that.info.receiver_mobile = content.receive_phone
						that.info.receiver_address = content.receive_address
					} else {
						uni.showModal({
							title: '提示',
							content: `数据解析失败！请检查发货信息内容，或联系技术人员。错误信息：${response.msg}`,
							showCancel: false,
							success: (res) => {}
						})
					}
				} else {
					uni.showModal({
						title: '提示',
						content: `数据解析失败！请检查发货信息内容，或联系技术人员。错误信息：${response.msg}`,
						showCancel: false,
						success: (res) => {}
					})
				}
			},

			// 接口:火山引擎(豆包AI)
			async arkAnalyze() {
				let that = this
				uni.showLoading({ title: '识别中..', mask: true, })
				let user_token = getUInfo().token

				let image_url = this.img_url
				let text = '分析图片中客户简称中的姓名(只要人的姓名)、客户地址、客户电话、总件数、总重量，摘要，指定，以json格式输出，键名分别为name，address，phone，num，weight，remark，sign'

				let response = await that.$arkAnalyze2({ image_url, text })
				if (response.code == 1) {
					let res = JSON.parse(response.data)
					if (res && res.choices && res.choices.length > 0 && res.choices[0].message && res.choices[0].message.content) {
						let contentObj = null
						try {
							contentObj = JSON.parse(res.choices[0].message.content)
						} catch (e) {}
						if (contentObj) {
							that.info.receiver_name = contentObj.name
							that.info.receiver_mobile = contentObj.phone
							that.info.receiver_address = contentObj.address
							that.info.num = contentObj.num
							that.info.weight = parseFloat(contentObj.weight).toFixed(2)
							// 体积 = 吨数 * 2
							that.info.volume = parseFloat(contentObj.weight / 500).toFixed(2)
							that.info.remark = contentObj.remark
							uni.showToast({ title: '图片识别成功', icon: 'none', duration: 3000 })
						}
					}
				} else {
					// uni.showToast({ title: '图片识别失败', icon: 'none' })
					uni.showModal({
						title: '提示',
						content: `图片识别失败！请检查图片是否清晰，或联系技术人员。错误信息：${response.msg}`,
						showCancel: false,
						success: (res) => {}
					})
				}
			},

			// 接口:提交信息
			async postData() {
				let that = this
				let token = getUInfo().token
				uni.showLoading({ title: '提交中..', mask: true, })
				let remark = this.info.remark
				let receiver_name = this.info.receiver_name
				let receiver_mobile = this.info.receiver_mobile
				let receiver_address = this.info.receiver_address
				let goods = JSON.stringify([{
					goods_name: this.info.goods_name,
					goods_num: this.info.num,
					goods_volume: this.info.volume,
					goods_weight: this.info.weight,
					unit: 'kg',
				}])
				let res = await that.$create_order({ token, remark, receiver_name, receiver_mobile, receiver_address, goods })
				if (res.code == 1) {
					uni.showModal({
						title: '提示',
						content: res.msg,
						confirmText: '继续下单',
						success: (res) => {
							if (res.confirm) {
								that.resetData()
							}
						}
					})
				} else {
					uni.showToast({ title: res.msg, icon: 'none' })
				}
			},

			// 重置数据
			resetData() {
				this.img_url = ''
				this.info = {
					receiver_name: '',
					receiver_mobile: '',
					receiver_address: '',
					goods_name: '火腿肠',
					num: '',
					weight: '',
					volume: 1,
					remark: '',
				}
			},

			md5(str) {
				try {
					return CryptoJS.MD5(str).toString()
				} catch (error) {}
				return 'md5_error'
			}

		}
	}
</script>

<style scoped>
	.content {
		display: flex;
		flex-direction: column;
		position: relative;
		min-height: 100vh;
		background-color: #6974DD;
		/* background-color: #f0f0f0; */
	}

	.main {
		display: flex;
		flex-direction: column;
		margin: 24rpx;
		background-color: white;
		border-radius: 24rpx;
		padding: 24rpx;
	}

	.menu_name {
		display: flex;
		align-items: center;
		font-weight: bold;
		margin: 36rpx 0 0 0;
	}

	.sub_menu_name {
		margin: 12rpx 0 0 0;
	}

	.btn_wb {
		width: 25%;
		height: 76rpx;
		line-height: 76rpx;
		color: white;
		text-align: center;
		font-size: 28rpx;
		margin: 24rpx 0 0 0;
		border-radius: 12rpx;
		background: #6974DD;
		margin: 24rpx 0 0 12rpx;
	}

	/* 选择异常原因 */
	.yc_reason {
		display: flex;
		justify-content: space-between;
		height: 76rpx;
		line-height: 76rpx;
		border-radius: 12rpx;
		border: solid 1rpx #ccc;
		margin: 24rpx 0 0 0;
		padding: 0 24rpx 0 24rpx;
	}

	.item_sel_img {
		display: flex;
		width: 100%;
		margin: 12rpx 0 12rpx 0;
	}

	.sel_img_div {
		display: flex;
		flex-direction: column;
		align-items: center;
	}

	/* 选择的照片 */
	.sel_img {
		width: 120rpx;
		height: 120rpx;
		margin: 0 0 0 16rpx;
		border: solid 1rpx #999;
		border-radius: 12rpx;
		/* padding: 1rpx; */
	}

	.sel_img_del {
		padding: 6rpx;
		color: orangered;
		margin: 0 0 0 16rpx;
	}

	.et_desc {
		width: calc(100% - 48rpx);
		height: 200rpx;
		font-size: 26rpx;
		border-radius: 12rpx;
		border: solid 1rpx #f0f0f0;
		margin: 24rpx 0 0 0;
		padding: 24rpx;
	}

	.btn_analysis {
		align-self: center;
		width: 44%;
		height: 88rpx;
		line-height: 88rpx;
		text-align: center;
		color: white;
		background: #6974DD;
		border-radius: 888rpx;
		margin: 24rpx 0 0 0;
	}

	.btn_sel_media {
		width: 300rpx;
		height: 66rpx;
		line-height: 66rpx;
		font-size: 28rpx;
	}

	.btn_ok {
		height: 88rpx;
		line-height: 88rpx;
		color: white;
		text-align: center;
		font-size: 30rpx;
		margin: 12rpx 0 0 0;
		border-radius: 888rpx;
		background: #6974DD;
	}

	/* pop弹窗样式 */
	.pop_div {
		display: flex;
		flex-direction: column;
		align-items: center;
		justify-content: center;
		width: 75vw;
		background-color: white;
	}

	/* 下单模块 */
	.item_div {
		display: flex;
		flex-direction: column;
		margin: 24rpx 24rpx 24rpx 24rpx;
		padding: 24rpx;
		background-color: white;
		border: solid 1rpx #f0f0f0;
		border-radius: 16rpx;
	}

	.item_sub_div {
		display: flex;
		align-items: center;
		justify-content: space-between;
		height: 96rpx;
		margin: 10rpx 0 0 0;
	}

	.item_sub_txt {
		font-size: 28rpx;
		font-weight: bold;
		margin: 0rpx 0 0 0rpx;
	}

	.et_sub_txt {
		width: 60%;
		height: 100%;
		text-align: right;
		font-size: 28rpx;
		color: #555;
	}
</style>